import sys
import socket
from threading import Thread

class baseServerHandler:
	def __init__(self, clientsock, client_address, HandleArgs={}):
		self.clientsock = clientsock
		self.client_address = client_address
		self.args = HandleArgs
		self.setup()
		try:
			self.handle()
		except Exception as e:
			print(self.client_address, e)
		finally:
			self.finish()
	def handle(self):
		while True:
			self.data=self.clientsock.recv(2048)
			if len(self.data) > 0:
				self.recvDataDispose(self.data)
				# self.sendData(self.data)
			else :
				raise IOError("--连接断开--")
	def setup(self):
		print("before handle,连接建立：",self.client_address)
		pass
	def finish(self):
		print("finish run  after handle")
		pass
	def recvDataDispose(self, data):
		print("{} sends:".format(self.client_address),self.data)
	def sendData(self, data):
		self.clientsock.sendall(data)

# TCP服务器类
class TCPServer:
	def __init__(self, host="", port=4001, Handler=baseServerHandler, HandleArgs={}):
		# 初始化参数
		self.host = host
		self.port = port
		self.client = {}
		self.Handler = Handler
		self.HandleArgs = HandleArgs
		# 开始运行服务器
		self.start()

	def __del__(self):
		try:
			self.stop()
		except Exception as e:
			print("已经停止过server")
		finally:
			print("删除对象：", self)

	def ServerHandle(self, clientsock, clientaddress, Handler):	# 服务器数据处理线程入口
		Handler(clientsock, clientaddress, self.HandleArgs)			# 处理服务器数据
		clientsock.close()						# 关闭socket
		print("remove client ", (clientsock, clientaddress))
		del self.client[clientaddress]			# 删除client列表中的表项

	def TCPHandle(self):		# TCP连接的处理
		self.socket.bind((self.host, self.port))	# 绑定端口
		self.socket.listen(1)						# 监听socket
		try:
			while True:
				clientsock, clientaddress = self.socket.accept()		# 创建客户端线程处理数据
				print('connect from:', (clientsock, clientaddress))
				tid = Thread(target=self.ServerHandle, args=(clientsock, clientaddress, self.Handler))
				self.client[clientaddress] = (clientsock, tid) 			# 挂载到客户端列表
				tid.start()
		except OSError as e:
			print(self, e)
		finally:
			self.socket.close()
		print("TCPHandle线程退出")
		del self

	def start(self):			# 启动服务器
		# 创建socket，创建连接处理线程
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.HandleArgs["host"] = self			# 在HandleArgs中加入主机的对象引用
		self.thread = Thread(target = self.TCPHandle)
		self.thread.start()

	def stop(self):				# 停止服务器
		self.disconnet()
		self.socket.close()
		self.thread.join()
		# print(sys.getrefcount(self.thread))
		# print(sys.getrefcount(self.socket))
		del self.thread
		del self.socket

	def join(self):				# 等待连接处理线程退出
		self.thread.join()

	def disconnet(self):				# 断开所有连接
		print("正在关闭所有连接...")
		for i in self.client:
			self.client[i][0].close()
		# for i in self.client:
		# 	self.client[i][1].join()
		print("已关闭所有连接")
	def getClientList(self):
		client = []
		for key in self.client:
			client.append(key)
		return client
	def sendClient(self, clientaddress, data):
		try:
			self.client[clientaddress][0].sendall(data.encode("ascii"))
		except Exception as e:
			print(e)

if __name__=="__main__":		# 测试程序
	server = TCPServer(port=8001)
	while True:
		cmd = input("cmd->")
		if cmd == "disconnet":
			server.disconnet()
		elif cmd == "start":
			server.start()
		elif cmd == "print":
			print("server.client:")
			print(server.client)
		elif cmd == "delete":
			print("del server")
			del server
		elif cmd == "getref":
			print(sys.getrefcount(server))
		elif cmd == "stop":
			server.stop()
			print("server.stop()")
		elif cmd == "client":
			print(server.getClientList())
		elif cmd == "host-type":
			print(server.getClientList()[0])
			print(type(server.getClientList()[0]))
			print(server.getClientList()[0][0])
			print(type(server.getClientList()[0][0]))
			print(server.getClientList()[0][1])
			print(type(server.getClientList()[0][1]))


